package teamCservlets;
import java.io.Serializable;
import java.sql.Time;
import java.text.SimpleDateFormat;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class DatabaseInterface {

	// Key fields:

	// Username and password.

	protected String username;
	protected String password;

	// Connection, Statement, and ResultSet fields.
	// OBJECTS OF THIS CLASS ARE INVOKED IN SEPARATE THREADS
	// SO ONE THREAD WILL NOT ACCESS ANOTHER THREAD'S CONNECTION/STATEMENT/RESULTSET!

	protected Connection connection;
	protected PreparedStatement preparedStatement;
	protected ResultSet resultSet;

	// constructor.

	public DatabaseInterface () {
		// Set username and password for the MySQL database.
		username = new String("STRAWMAN");
		password = new String("PASSWORD123");

		// Set up the driver and create the connection and statement
		// objects.  Be sure to set up logging as well.

		try {

			// Load the database driver.

			Class.forName("com.mysql.jdbc.Driver");

			// Get the connection set up.

			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/DEFECT_DATABASE",username,password);

			if(connection == null) {
				LogWarning("WARNING: Database connection null!");
			} else {
				LogInfo("Database connection established!");
			}

		} catch (ClassNotFoundException cnfe) {
			LogException(cnfe);
		} catch (SQLException sqle) {
			LogException(sqle);
		} catch (Exception e) {
			LogException(e);
		}
	} // End constructor

	protected boolean runSQLstatement() {
		try {

			// Execute it!

			preparedStatement.execute();

			// Obtain the result set.

			resultSet = preparedStatement.getResultSet();

			// If a result is returned, set to true.  Otherwise false.
			if(resultSet != null) {
				return true;
			} else {
				return false;
			}

		} catch (SQLException sqle) {
			LogException(sqle);
			return false;
		} catch (NullPointerException npe) {
			LogException(npe);
			return false;
		} catch (Exception e) {
			LogException(e);
			return false;
		}

	} // End method to run SQL statement

	// Method to log exceptions
	protected void LogException(Exception e) {

		// Code to log exceptions goes here.

		// Set up a logger to log events.
		try {
			Logger ExceptionLogger = Logger.getLogger(Exception.class.getName());
			FileHandler ExceptionHandler = new FileHandler("MySQLexceptionLog.txt");

			ExceptionLogger.setLevel(Level.WARNING);
			ExceptionLogger.addHandler(ExceptionHandler);
			ExceptionHandler.setLevel(Level.WARNING);
			ExceptionHandler.setFormatter(new SimpleFormatter());

			ExceptionLogger.info("Exception caught");
			ExceptionLogger.info("Message = " + e.getMessage());
		} catch (IOException ioe) {
			System.out.println("ERROR: IOException thrown when trying to log exceptions!");
			System.out.println(ioe.getMessage());
		} catch (Exception ee) {
			System.out.println("ERROR: Generic exception in LogException!");
			System.out.println(ee.getMessage());
		}

	} // End method LogException

	protected void LogWarning(String errorMessage) {
		try {
				// Set up the logger.

				Logger logger = Logger.getLogger(DatabaseInterface.class.getName());
				FileHandler handler = new FileHandler("MySQLwarningLog.txt");

				logger.setLevel(Level.WARNING);
				logger.addHandler(handler);
				handler.setLevel(Level.WARNING);
				handler.setFormatter(new SimpleFormatter());

				logger.warning(errorMessage);
			} catch(IOException ioe) {
				System.out.println("ERROR: Unable to run warning log due to IOException.  Message below:");
				System.out.println(ioe.getMessage());
			}

	} // End method LogError

	protected void LogInfo(String message) {
		try {
				// Set up the logger.

				Logger logger = Logger.getLogger(DatabaseInterface.class.getName());
				FileHandler handler = new FileHandler("MySQLinfoLog.txt");

				logger.setLevel(Level.INFO);
				logger.addHandler(handler);
				handler.setLevel(Level.INFO);
				handler.setFormatter(new SimpleFormatter());

				logger.warning(message);
			} catch(IOException ioe) {
				System.out.println("ERROR: Unable to run info log due to IOException.  Message below:");
				System.out.println(ioe.getMessage());
			}

	} // End method LogInfo

	// The cleanup method closes the statement (and with it, any open ResultSet objects)
	// as well as the connection object.

	protected boolean cleanup() {

		try {
			// Close the statement and any of its ResultSets.

			preparedStatement.close();

			// Close the connection.

			connection.close();

			// Return true to indicate success.

			return true;
		} catch (SQLException sqle) {
			// Log this exception.
			LogException(sqle);

			// Return false to indicate a failure.
			return false;
		} catch (Exception e) {
			LogException(e);
			return false;
		}
	} // End method cleanup
} // End DatabaseInterface